package com.jycrm.service.serve;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.SQLException;

import com.jycrm.common.PagedListHolder;
import com.jycrm.dao.serve.IReckoningDao;
import com.jycrm.service.core.GenericServiceException;

public class ReckoningConversionThread  implements Runnable{
	
	private IReckoningDao reckoningDao;
	private int start;
	private int end;
	private String path;
	
	public ReckoningConversionThread(IReckoningDao reckoningDao,int start,int end, String path){
		this.reckoningDao=reckoningDao;
		this.start=start;
		this.end=end;
		this.path=path;
	}
	

	public void run() {
		File file=new File(path);
		try {
			conversionThead( start, end,file);
		} catch (IOException e) {
			
			e.printStackTrace();
			throw new GenericServiceException(e.getMessage());
		} catch (SQLException e) {
			
			e.printStackTrace();
			throw new GenericServiceException(e.getMessage());
		}
		
	}

private void conversionThead(int start,int end, File file) throws IOException, SQLException{
	System.gc();
	FileOutputStream fileStream =null;
	BufferedWriter writer =null;
		try {			
			final int pageSize=2000;	
			StringBuffer sqlPrifix = new StringBuffer()
			
			.append(" select taaccountid from (select  a.*,ROWNUM RN from(")
			.append("  select t.taaccountid as taAccountId	from crm_dzd_custinfo t order by t.taaccountid " );
			
			
			 fileStream = new FileOutputStream(file,true);
			 writer= new BufferedWriter(new OutputStreamWriter(
					fileStream, "GBK"));
			 
			//saveToFile(info,file);
			int total= reckoningDao.getReckoningCustomerInfoForThreadTotal(new Long(start),new Long(end));
			PagedListHolder p = new PagedListHolder();

			p.setPageSize(pageSize);
			p.setTotal(total);
			int pageCount=p.getPageCount();
			for (int i = 0; i < pageCount; i++) {
				int rowStart = i * p.getPageSize() + start;
				int  rowEnd =p.getPageSize() * (i + 1)+ start-1;
				rowEnd=rowEnd>end?end:rowEnd;
				StringBuffer sql = new StringBuffer(sqlPrifix.toString())
				.append("  )a where ROWNUM <="+rowEnd+"	)WHERE RN >= "+rowStart);
				reckoningDao.getReckoningDzdInfo(sql.toString(), writer);
			}
			
			writer.flush();	
			fileStream.flush();
			
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		throw e;
		
	}finally{
		if(writer!=null){writer.close();}
		if(fileStream!=null){fileStream.close();}
	}
		
	}
	
	
	
	
}
